import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import { Role } from '../../entities/role.entity';
import { Permission } from 'src/entities/permission.entity';
/**
 * 角色服务
 *
 * 职责：
 * 1. 角色的 CRUD 操作
 * 2. 角色权限的关联管理
 * 3. 查询角色的权限列表
 */

@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(Role)
    private readonly roleRepository: Repository<Role>,

    @InjectRepository(Permission)
    private readonly permissionRepository: Repository<Permission>,
  ) {}

  /**
   *  创建角色
   * */

  async create(createRoleDto: {
    name: string;
    displayName: string;
    description?: string;
    level?: number;
  }) {
    const role = this.roleRepository.create(createRoleDto);
    return await this.roleRepository.save(role);
  }

  /**
   *  查找所有角色
   *
   */
  async findAll() {
    return await this.roleRepository.find({
      relations: ['permissions'], // 关联加载权限
      order: { level: 'DESC' }, // 按等级降序
    });
  }

  /**
   * 查找单个角色
   *
   */
  async findOne(id: string) {
    const role = await this.roleRepository.findOne({
      where: { id },
      relations: ['permissions'],
    });
    if (!role) {
      throw new NotFoundException('角色不存在');
    }
    return role;
  }

  /**
   * 根据角色名查找
   *
   */
  async findByName(name: string) {
    return await this.roleRepository.findOne({
      where: { name },
      relations: ['permissions'],
    });
  }

  /**
   * 为角色分配权限
   *  @param roleId 角色ID
   *  @param permissionIds 权限ID数组
   * */

  async assignPermissions(roleId: string, permissionIds: string[]) {
    // 1.查找角色
    const role = await this.findOne(roleId);

    // 2.查找权限
    const permissions = await this.permissionRepository.findBy({
      id: In(permissionIds),
    });
    if (permissions.length !== permissionIds.length) {
      throw new NotFoundException('部分权限不存在');
    }

    // 3.分配权限
    role.permissions = permissions;

    // 4.保存
    return await this.roleRepository.save(role);
  }

  /**
   * 移除角色的权限
   */
  async removePermissions(roleId: string, permissionIds: string[]) {
    const role = await this.findOne(roleId);

    // 过滤掉要移除的权限
    role.permissions = role.permissions.filter(
      (p) => !permissionIds.includes(p.id),
    );

    return await this.roleRepository.save(role);
  }

  /**
   * 获取角色的所有权限
   * 返回权限名称数组
   */
  async getRolePermissions(roleId: string): Promise<string[]> {
    const role = await this.findOne(roleId);
    return role.permissions.map((p) => p.name);
  }

  /**
   * 检查角色是否拥有某个权限
   */
  async hasPermission(
    roleId: string,
    permissionName: string,
  ): Promise<boolean> {
    const permissions = await this.getRolePermissions(roleId);
    return permissions.includes(permissionName);
  }

  /**
   * 删除角色
   */
  async remove(id: string) {
    const role = await this.findOne(id);

    // 系统角色不能删除
    if (role.isSystem) {
      throw new Error('系统角色不能删除');
    }

    await this.roleRepository.softDelete(id);
    return { message: '删除成功' };
  }
}
